<template>
  <div>
    <a-modal
      title="$t('momentCreateForm.pfrw')"
      style="top:0;margin-top:0;"
      width="90%"
      :visible="visible"
      :confirmLoading="confirmLoading"
      @ok="handleSubmit"
      @cancel="handleCancelDialog"
    >
      <a-spin :spinning="confirmLoading">
        <a-form :form="form">
          <a-form-item
            label="$t('momentCreateForm.mc')"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
          >
            <a-input v-decorator="['title', {rules: [{required: true, message: '$t('momentCreateForm.bnwk')'}]}]" />
          </a-form-item>
          <a-form-item
            label="$t('momentCreateForm.wb')"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
          >
            <a-textarea placeholder="" v-model="formData.desc" :rows="6" />
          </a-form-item>
          <a-form-item
            label="$t('momentCreateForm.tp')"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
          >
            <a-upload
              name="file"
              accept="jpg,jpeg,png,bmp"
              :action="uploadUrl"
              :headers="uploadHeaders"
              :multiple="true"
              listType="picture-card"
              @preview="handlePreview"
              @change="handleUploadChange"
            >
              <div v-if="fileList.length < 9">
                <a-icon type="plus" />
                <div class="ant-upload-text">Upload</div>
              </div>
            </a-upload>

          </a-form-item>
          <a-form-item
            label="$t('momentCreateForm.lj')"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
          >
            <a-input v-model="formData.url" />
          </a-form-item>
          <a-form-item
            label="$t('momentCreateForm.jdyq')"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
          >
            <a-radio-group v-decorator="['level', {rules: [{required: true, message: '{{ $t('momentCreateForm.bnwk') }}'}]}]" buttonStyle="solid">
              <a-radio-button :value="item.value" v-for="item in vipOptions">{{item.label}}</a-radio-button>
            </a-radio-group>
          </a-form-item>
          <a-form-item
            label="$t('momentCreateForm.sl')"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
          >
            <a-input v-decorator="['cnt', {rules: [{required: true, message: '{{ $t('momentCreateForm.znsrzs') }}'}]}]" />
          </a-form-item>
          <a-form-item
            label="$t('momentCreateForm.mdjl')"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
          >
            <a-input v-decorator="['reward', {rules: [{required: true, message: '{{ $t('momentCreateForm.znsrzs') }}'}]}]" />
          </a-form-item>
        </a-form>
      </a-spin>
    </a-modal>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>

<script>
import { ACCESS_TOKEN } from '@/store/mutation-types'

function getBase64 (file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}

export default {
  components: { },
  data () {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 17 }
      },
      visible: false,
      confirmLoading: false,
      form: this.$form.createForm(this),
      vipOptions: [{
        label: this.$t('momentCreateForm.syhy'),
        value: '0'
      }],
      loadingParse: false,
      formData: {
        title: '',
        desc: '',
        url: '',
        imgs: '',
        cnt: '',
        vip_level: '0',
        type: '0',
        reward: ''
      },
      previewVisible: false,
      previewImage: '',
      fileList: [],
      uploadHeaders: {
        authorization: 'authorization-text'
      },
      uploadUrl: ''
    }
  },
  methods: {
    add () {
      this.visible = true
    },
    handleChangeEditor (val) {
      this.formData.desc = val
    },
    handleCancel () {
      this.previewVisible = false
    },
    async handlePreview (file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    handleUploadChange (info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        let resp = info.file.response
        if (resp.code === 0) {
          this.fileList.push(resp.data)
        }
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} file upload failed.`)
      } else if (info.file.status === 'removed') {
        let filename = info.file.response.data
        let newArr = []
        for (let i = 0; i < this.fileList.length; i++) {
          if (this.fileList[i] != filename) {
            newArr.push(this.fileList[i])
          }
        }
        this.fileList = newArr
      }
    },
    handleSubmit () {
      console.log(this.formData)
      const { form: { validateFields } } = this
      this.confirmLoading = true
      validateFields((errors, values) => {
        if (!errors) {
          console.log(values)
          this.formData.cnt = values.cnt
          this.formData.title = values.title
          this.formData.reward = values.reward
          this.formData.imgs = this.fileList.join(',')
          console.log('values', this.formData)
          setTimeout(() => {
            this.visible = false
            this.confirmLoading = false
            this.$emit('ok', this.formData)
          }, 1500)
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleChangeType (e) {
      this.formData.type = e.target.value
    },
    handleChangeLevel (e) {
      this.formData.vip_level = e.target.value
    },
    handleCancelDialog () {
      this.visible = false
    },
    getVipList () {
      this.$http.get('/member/card_list').then(res => {
        this.vipOptions = [{
          label: this.$t('momentCreateForm.syhy'),
          value: '0'
        }]
        for (let i = 0; i < res.length; i++) {
          this.vipOptions.push({
            label: res[i].name,
            value: res[i].level
          })
        }
      }).catch(err => {
        this.$notification.error({
          message: this.$t('momentCreateForm.sb'),
          description: err.message
        })
      })
    },
    loadToken () {
      const token = this.$ls.get(ACCESS_TOKEN)
      if (token) {
        this.uploadHeaders.authorization = 'Bearer ' + token // 让每个请求携带自定义 token 请根据实际情况自行修改
      }
    }
  },
  created () {
    this.getVipList()
    this.uploadUrl = process.env.VUE_APP_API_BASE_URL + 'banner/upload'
    this.loadToken()
  }
}
</script>
